package org.apak.frontend;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apak.db.RepairServiceDAO;
import org.apak.log.FileLogger;
import org.apak.model.LoggedSubject;
import org.apak.model.ServiceOrder;

/**
 * Servlet implementation class MainServlet
 */
public class MainServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private RepairServiceDAO dao = new RepairServiceDAO();
	private HttpSession session;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		session = request.getSession(true);
		FileLogger.logMessage("Forwarded to main.jsp by MainServlet.");
		RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
		dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String actionButton = request.getParameter("actionButton");
		LoggedSubject loggedSubject = null;
		if(actionButton != null)
			if(actionButton.equals("Log me in")) {
				loggedSubject = dao.getLoggedSubject(request.getParameter("login"), request.getParameter("pass"));
				if(loggedSubject != null) {
					session.setAttribute("loggedSubject", loggedSubject);
					if(loggedSubject.isCustomer()) 
						response.sendRedirect("./serviceOrderMenu");
					else
						response.sendRedirect("./serviceRequestMenu");
				} else {
					request.setAttribute("login", request.getParameter("login"));
					request.setAttribute("error", "Wrong login or password!");
					RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
					dispatcher.forward(request, response);
				}
			}
	}

}
